<?php

namespace app\admin\controller\health\goods;

use app\common\controller\Backend;
use app\health\model\HealthGoods;
use app\health\model\HealthGoodsCategory;
use Exception;
use think\Db;

class Goods extends Backend
{
    /**
     * HealthGoods
     * @var HealthGoods
     */
    protected $model = null;

    protected $relationSearch = false;
    protected $searchFields = 'name,goods_code';
    protected $multiFields = ['is_enable'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new HealthGoods();
        $tags = [];
        foreach (HealthGoods::TAG_MAP as $id => $title) {
            $tags[] = compact('id', 'title');
        }
        $this->assign('tags', $tags);
        $this->assign('category', HealthGoodsCategory::where([])->field('id,name')->order('sort', 'desc')->select());
    }

    /**
     * 构建查询提交
     * @return $query
     * @Author 张旭鹏
     * @DateTime 2023-06-21
     */
    protected function buildSearchWhere()
    {
        $isEnable = $this->request->get("is_enable");
        $goodsIds = $this->request->get("goods_ids");
        $goodsName = $this->request->get("goods_name", '');        // 关键字
        $goods = $this->model;
        if ($goodsName) {
            $goods = $goods->where('goods_name', "LIKE", "%{$goodsName}%");
        }
        if ($isEnable != '') {
            $goods = $goods->where('is_enable', $isEnable);
        }
        if ($goodsIds) {
            $goods = $goods->whereIn('id', $goodsIds);
        }
        return $goods;
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->buildSearchWhere()->count();
            $list = $this->buildSearchWhere()
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $item) {
                $item->append(['tag_text']);
            }
            $result = array("total" => $total, "rows" => $list);
            return $this->success('操作成功', null, $result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                // 启动事务
                Db::startTrans();
                try {
                    //先添加商品主表
                    $params['add_time'] = time();
                    $goods_id = $this->model->insertGetId($params);
                    $attr = $this->request->post();
                    $totalStock = 0;
                    foreach ($attr['attr'] as $k => $v) {
                        $data[$k]['goods_id'] = $goods_id;
                        $data[$k]['attr_name'] = $v;
                        $data[$k]['image'] = $attr['images'][$k];
                        $data[$k]['price'] = $attr['price'][$k];
                        $data[$k]['stock'] = $attr['stock'][$k];
                        $totalStock += $attr['stock'][$k];
                    }
                    $this->model->where('id', $goods_id)->update(['stock' => $totalStock]);
                    //再添加规格属性表
                    $result = $this->model->goodsAttr()->insertAll($data);
                    // 提交事务
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty'));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //先修改商品主表
                    $params['upd_time'] = time();
                    $attr = $this->request->post();
                    $params['stock'] = 0;
                    foreach ($attr['attr'] as $k => $v) {
                        $data[$k]['goods_id'] = $row['id'];
                        $data[$k]['attr_name'] = $v;
                        $data[$k]['image'] = $attr['images'][$k];
                        $data[$k]['price'] = $attr['price'][$k];
                        $data[$k]['stock'] = $attr['stock'][$k];
                        $params['stock']  += $attr['stock'][$k];
                    }
                    $this->model->where('id', $row['id'])->update($params);
                    //先删除再添加
                    $result = $this->model->goodsAttr()->where('goods_id', $row['id'])->delete();
                    //再添加规格属性表
                    $result = $this->model->goodsAttr()->insertAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty'));
        }
        $this->view->assign("row", $row);
        //查找规格属性表信息
        $attr = $this->model->goodsAttr()->where('goods_id', $row['id'])->column('*');
        sort($attr);
        $this->view->assign("attr", $attr);
        return $this->view->fetch();
    }


    /**
     * 删除商品
     * @Author 张旭鹏
     * @DateTime 2023-06-13
     */
    public function delete()
    {
        $id  = input('ids');
        $res = $this->model->where('id', $id)->update(['is_del' => 2]);
        if ($res !== false) {
            $this->success();
        } else {
            $this->error(__('删除失败'));
        }
    }

    /**
     * 选择商品
     * @Author 张旭鹏
     * @DateTime 2023-07-04
     */
    public function select()
    {
        if ($this->request->isAjax()) {
            return $this->index();
        }
        $categoryModel = new HealthGoodsCategory;
        $category = $categoryModel->order('sort desc, id asc')->select();
        $this->assignconfig('category', $category);
        return $this->view->fetch();
    }

    /**
     * 修改商品状态
     * @param [type] $ids
     * @param [type] $status
     * @Author 张旭鹏
     * @DateTime 2023-07-04
     */
    public function setStatus($ids, $status)
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $result = $this->model->where($pk, 'in', $ids)->update([
                'is_enable' => $status == 'down' ? 0 : 1
            ]);
            if ($result) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        }
        $this->error('请选择商品');
    }
}
